#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/12/21 15:22
# @Author  : CHEN Wang
# @Site    :
# @File    : file_tool.py
# @Software: PyCharm

"""
脚本说明: 操作文件夹及文件
"""

import hashlib
import re
import os
import shutil


def copy_file(source_file_path, target_folder_path):
    """
    文件拷贝

    :param source_file_path: 源文件路径与文件名
    :param target_folder_path: 目标文件夹路径
    :return:
    """
    # sourcePath = r'E:\python\copy_file\1\123.txt'
    # targetPath = r'E:\python\copy_file\2'
    shutil.copy(source_file_path, target_folder_path)


class FileBackup(object):
    """文本文件备份"""

    def __init__(self, src, dist):
        """
        构造方法
        :param src:  需要备份的文件目录
        :param dist: 备份后的目录
        """
        self.src = src
        self.dist = dist

    def read_files(self):
        """
        读取src目录下的所有文件
        :return:
        """
        ls = os.listdir(self.src)
        print(ls)  # 查看一下当前目录所有的文件
        for l in ls:
            # 循环处理每一个文件
            self.backup_file(l)

    def backup_file(self, file_name):
        """
        处理备份
        :param file_name: 文件/文件夹的名称
        :return:
        """

        # 1、判断dist目录是否存在，如果不存在，创建目录
        if not os.path.exists(self.dist):
            os.makedirs(self.dist)
            print("指定的目录不存在，创建完成")
        # 2、判断文件是否为我们要备份
        # 得到的是文件名 拼接文件的完整路径
        full_src_path = os.path.join(self.src, file_name)
        full_dist_path = os.path.join(self.dist, file_name)
        # 首先判断是否为文件夹，然后借助文件后缀名判断
        if os.path.isfile(full_src_path) and os.path.splitext(full_src_path)[-1].lower() == '.txt':
            # print(full_src_path)  # 打印看一下要备份的文件完整目录
            with open(full_dist_path, 'w', encoding='utf-8')as f_dist, \
                    open(full_src_path, 'r', encoding='utf-8')as f_src:
                print(">>开始备份【{0}】".format(file_name))
                # 3、读取文件内容
                while True:
                    rest = f_src.read(100)
                    if not rest:
                        break
                    # 4、把读取到的内容写入新的文件中
                    f_dist.write(rest)
                f_dist.flush()  # 把剩余没写进去的全部写出去
                print(">>【{0}】备份完成".format(file_name))

        else:
            print("文件类型不符合要求，跳过>>")


def QA_util_file_md5(filename):
    
    """
    explanation:
        获取文件的MD5值		

    params:
        * filename ->:
            meaning: 文件路径
            type: null
            optional: [null]

    return:
        str
	
    demonstrate:
        Not described
	
    output:
        Not described
    """

    with open(filename, mode='rb') as f:
        d = hashlib.md5()
        while True:
            # 128 is smaller than the typical filesystem block
            buf = f.read(4096)
            if not buf:
                break
            d.update(buf)
        return d.hexdigest()


def QA_util_file_size(file):
    return os.path.getsize(file)


def get_all_filename_path(file_path, all_file=False, re_condition=''):
    """
    寻找文件夹下的所有文件路径(包括子目录下的文件)

    :param str file_path: 文件地址 如f"E:\指标数据\\trading_data\ohlcv"
    :param bool all_file: 是否包含子目录下的文件
    :param str re_condition: 正则表达式条件 如 '.*\d.*'
    :return:
        {'Binance_BTCUSDT_d.csv': 'E:\\指标数据\\trading_data\\ohlcv\\Binance_BTCUSDT_d.csv',
        'Bitfinex_BTCUSD_d.csv': 'E:\\指标数据\\trading_data\\ohlcv\\Bitfinex_BTCUSD_d.csv',
        'Bitstamp_BTCUSD_d.csv': 'E:\\指标数据\\trading_data\\ohlcv\\Bitstamp_BTCUSD_d.csv',}
    """

    all_filename_path = []
    for root, dirs, files in os.walk(file_path):
        # root 表示当前正在访问的文件夹路径
        # dirs 表示该文件夹下的子目录名list
        # files 表示该文件夹下的文件list
        # 遍历文件

        if re_condition:
            for f in files:
                if re.match(f'{re_condition}', f):
                    all_filename_path.append(os.path.join(root, f))
        else:
            for f in files:
                all_filename_path.append(os.path.join(root, f))

        # # 遍历所有的文件夹
        # for d in dirs:
        #     print(os.path.join(root, d))
        if not all_file:
            break

    all_filename_path_dict = dict(zip(files, all_filename_path))

    return all_filename_path_dict


if __name__ == '__main__':
    # 数据拷贝
    from quant_researcher.quant.project_tool.localize import DATA_DIR
    file_name = os.path.join(DATA_DIR, f'test')
    backup_path = os.path.join(DATA_DIR, f'all_history_ohlcvm_backup')
    copy_file(f'{file_name}.txt', backup_path)


    # # 要备份的文件目录地址
    # src_path = '/Users/wankcn/Desktop/PythonCode/python-project/src'
    # # 备份后的目录地址
    # dist_path = '/Users/wankcn/Desktop/PythonCode/python-project/dist'

    # 当前代码的目录名称
    base_path = os.path.dirname(os.path.abspath(__file__))
    src_path = os.path.join(base_path, 'src')  # 目录拼接
    dist_path = os.path.join(base_path, 'dist')
    print(src_path)
    print(dist_path)
    bak = FileBackup(src_path, dist_path)
    bak.read_files()

    x = get_all_filename_path(f"E:\指标数据\\trading_data\ohlcv")
    x = get_all_filename_path(f"E:\指标数据\\trading_data\ohlcv", all_file=False, re_condition=r'.*\d.*')